package com.example.webgobang.controller;

import com.example.webgobang.model.domin.ResponseFormat;
import com.example.webgobang.model.domin.User;
import com.example.webgobang.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.example.webgobang.common.Constants.SESSION_USER_KEY;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public ResponseFormat register(String username, String password, String checkPassword, HttpServletRequest request) {
        User user = userService.userRegister(username, password, checkPassword, request);
        if(user == null) {
            return ResponseFormat.fail("参数校验未通过");
        }
        return ResponseFormat.success(user);
    }

    @PostMapping("/login")
    public ResponseFormat login(String username, String password, HttpServletRequest request) {
        User user = userService.userLogin(username, password, request);
        if(user == null) {
            return ResponseFormat.fail("参数校验未通过");
        }
        return ResponseFormat.success(user);
    }

    @GetMapping("/userInfo")
    public User getUserInfo(HttpServletRequest request) {
        User dbUser = null;
        try {
            User user = (User) request.getSession(false).getAttribute(SESSION_USER_KEY);
            dbUser = userService.getUserById(user.getId());
        } catch (Exception e) {
            log.error("UserController-getUserInfo: " + e.getMessage());
        }
        return dbUser;
    }

    @GetMapping("/logout")
    public void logout(HttpSession session) {
        session.removeAttribute(SESSION_USER_KEY);
    }
}
